程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> [LeetCode]Recover Binary Search Tree

[LeetCode]Recover Binary Search Tree

編輯:關於C++

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

中序遍歷,用一個List存儲每個節點的位置,然後雙指針一個從左往右,一個從右往左找到連個錯誤的位置,然後交換連個節點的值。


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	List list = new ArrayList<>();
    public void recoverTree(TreeNode root) {
    	mid(root);
    	int left = -1;
    	int right = -1;
    	for(int i=0;ilist.get(i+1).val){
    			left = i;
    			break;
    		}
    	}
    	for(int j=list.size()-1;j>0;j--){
    		if(list.get(j).val

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved